package com.jxt.myapp.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jxt.myapp.domain.Menu;
import com.jxt.myapp.domain.User;
import com.jxt.myapp.service.IPermissionsService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	
	@Resource(name = "permissionsService")
	private IPermissionsService permissionsService;
	
	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Model model) {
		logger.info("Welcome home!");
		String loginName = getLoginName();
		User user = permissionsService.getUserByLoginName(loginName);
		logger.info("GroupID:"+user.getGroupId());
		List<Menu> menus = permissionsService.getMenuByGroupId(user.getGroupId());
		model.addAttribute("userMenus", menus);
		return "home";
	}

	/**
	 * 跳转到login页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String getLogin() {
		logger.info("Login!");
		return "login";
	}

	/**
	 * 跳转到denied页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/denied", method = RequestMethod.GET)
	public String getDenied() {
		logger.info("Denied!");
		return "denied";
	}

	/**
	 * 跳转到user页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toUser", method = RequestMethod.GET)
	public String getUser() {
		logger.info("ToUser!");
		return "user";
	}

	/**
	 * 跳转到group页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toGroup", method = RequestMethod.GET)
	public String getGroup() {
		logger.info("ToGroup!");
		return "group";
	}
	
	
	/**
	 * 获得登录名
	 */
	public static String getLoginName(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Authentication auth =securityContext.getAuthentication();
		Object principal=auth.getPrincipal();
		String loginName = "";
		if(principal instanceof UserDetails){
			loginName = ((UserDetails) principal).getUsername();
		}else{
			loginName = principal.toString();
		}
		return loginName;
	}

}
